//
//  SYTabBar.swift
//  YANAWeibo
//
//  Created by mac on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

// 设置代理
protocol SYTabBarDelegate: NSObjectProtocol {
    func didSelectedComposeButton()
}

class SYTabBar: UITabBar {
    //设置闭包
    var composeButtonClousre: (()->())?
    //设置代理
    weak var SYdelegate: SYTabBarDelegate?

     // MARK: - 使用懒加载
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        //添加点击事件
        button.addTarget(self, action: "composeButtomClick", forControlEvents: .TouchUpInside)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        button.sizeToFit()
        
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(composeButton)
    }
    
     // MARK: 加号按钮的监听
    @objc private func composeButtomClick() {
        //执行闭包
        composeButtonClousre?()
        //执行代理
        SYdelegate?.didSelectedComposeButton()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        let itemWith = frame.size.width / 5
        var index = 0
        //遍历子视图
        for childView in subviews {
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                childView.frame.size.width = itemWith
                childView.frame.origin.x = itemWith * CGFloat(index)
                index++
                
                if index == 2 {
                    index++
                }
                
            }
        }
        
    }
    
    
}
